package cn.java79.quiz.controller;

import cn.java79.quiz.entity.User;
import cn.java79.quiz.pojo.AjaxPage;
import cn.java79.quiz.pojo.MyUser;
import cn.java79.quiz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    //返回的String 是视图的地址
    //Model ==Map，直接放值
    @PostMapping("login")
    public String login(Model m, HttpSession session, String name, String pass,
                        @RequestParam(name = "code", required = true) String code) {

        if (name.startsWith("java79") && pass.startsWith("java79")) {
            m.addAttribute("msg", "登陆成功");
            session.setAttribute("USER_LOGIN", name);
            return "forward:/welcome.jsp";//视图解析器回导致找不到视图地址
            //return "/welcome.jsp";
        }
        m.addAttribute("msg", "错误的用户名或密码");
        return "forward:/fail.jsp";
    }

    //void表示没有视图
    @PostMapping("reg")
    public void reg(HttpServletResponse response, String username, String pass,
                    int[] like, String province,
                    @RequestParam(name = "age", defaultValue = "20") int age,
                    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") @RequestParam(name = "birthday", required = false) Date birthday, @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(name = "enterdate", required = false) Date enterdate) throws IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("<h1>" + username + "</h1>");
        writer.print("<h1>" + pass + "</h1>");
        writer.print("<h1>喜欢：" + Arrays.toString(like) + "</h1>");
        writer.print("<h1>年龄：" + age + "</h1>");
        writer.print("<h1>生日：" + birthday + "</h1>");
        writer.print("<h1>入学时间：" + enterdate + "</h1>");
        writer.print("<h1>province：" + province + "</h1>");
    }

    //请求中的参数和user的属性对应，自动创建MyUser对象，自动转换赋值
    @PostMapping("register")
    public void reg(HttpServletResponse response, MyUser user) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //...
        writer.print("<h1>" + user + "</h1>");
    }

    @GetMapping("toAdd")
    public String toAdd() {
        return "adduser";
    }

    @PostMapping("ureg")
    public String userreg(User user,
                          @RequestParam(name = "headpic2", required = false) MultipartFile file, RedirectAttributes rd, HttpServletRequest request) throws IOException {
        if (!file.isEmpty()) {
            //选了文件,获得存放的目录，不存在则创建
            String imgs = request.getServletContext().getRealPath("imgs");
            File f = new File(imgs);
            if (!f.exists())
                f.mkdir();
            //获得文件名
            String oldName = file.getOriginalFilename();
            //拿到后缀
            String suffix = oldName.substring(oldName.lastIndexOf('.'));
            String newName = UUID.randomUUID() + suffix;
            file.transferTo(new File(f, newName));//转移到目录下
            user.setHeadpic("imgs/" + newName);//保存新名称和路径 到对象中
        }
        this.userService.save(user);
        //显示一遍后自动删除
        rd.addFlashAttribute("msg", "新增学员成功");
        return "redirect:/user/search";
    }

    //删除
    @GetMapping("del-{id}")
    public String del(@PathVariable("id") Long id, RedirectAttributes rd) {
        int r = this.userService.del(id);
        rd.addFlashAttribute("msg", r > 0 ? "删除成功" : "删除失败");
        return "redirect:/user/search";
    }

    //修改
    @GetMapping("to-{id}")
    public String toUpdate(@PathVariable("id") Long id, Model m) {
        User user = this.userService.get(id);
        m.addAttribute("u", user);
        return "updateUser";
    }

    //update/100,
    @PostMapping("update-{id}")
    public String update(@PathVariable("id") Long id, User user) {
        user.setId(id);
        this.userService.update(user);
        //未完整
        return "xxxxx";
    }

    @GetMapping("search")
    public ModelAndView search(String loginname, String realname, String phone, @RequestParam(name = "pageNo", defaultValue = "1") int pageNo) {
//               loginname=loginname.substring(40);

        AjaxPage<User> p = this.userService.search(loginname, realname, phone, pageNo);
        ModelAndView mv = new ModelAndView();
        mv.addObject("p", p);
        mv.addObject("loginname", loginname);
        mv.addObject("realname", realname);
        mv.addObject("phone", phone);
        mv.setViewName("users");
        return mv;
    }
   /* @ExceptionHandler
    public String exce(Exception e){
        return "error";
    }*/

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        //true:允许输入空值，false:不能为空值
        //第二个参数，请求参数名
        binder.registerCustomEditor(Date.class, "enterdate", new CustomDateEditor(dateFormat, true));

        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        dateFormat2.setLenient(false);
        binder.registerCustomEditor(Date.class, "birthday", new CustomDateEditor(dateFormat2, true));
        // binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
